Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

Solution:

  1. public class Solution {
  2. public int longestValidParentheses(String s) {
  3. int i = -1, j = 0, max = 0;
  4. Stack<Integer> stack = new Stack<>();
  5. while (j < s.length()) {
  6. char c = s.charAt(j);
  7. if (c == '(') {
  8. stack.push(j);
  9. } else {
  10. if (stack.isEmpty()) {
  11. i = j;
  12. } else {
  13. stack.pop();
  14. max = Math.max(max, j - (stack.isEmpty() ? i : stack.peek()));
  15. }
  16. }
  17. j++;
  18. }
  19. return max;
  20. }
  21. }